package database

import (
	"cloudpichost/conf"
	"cloudpichost/pkg/util/pathdir"
	"fmt"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	_ "github.com/jinzhu/gorm/dialects/sqlite"
	"log"
	"sync"
)

var (
	db   *gorm.DB
	once sync.Once
)

func initDB() {
	var err error
	if conf.Setting.DBType == "mysql" {
		dsn := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8mb4&parseTime=True&loc=Local",
			conf.Setting.DBUser,
			conf.Setting.DBPwd,
			conf.Setting.DBHost,
			conf.Setting.DBTableName)
		db, err = gorm.Open(conf.Setting.DBType, dsn)
	} else if conf.Setting.DBType == "sqlite3" {
		db, err = gorm.Open(conf.Setting.DBType, conf.Setting.DBPath)
		if err != nil {
			// 尝试创建数据库文件
			if createErr := pathdir.CreateFile(conf.Setting.DBPath); createErr != nil {
				log.Fatalf("创建数据库文件失败: %v", err)
			}
		}
	}

	if err != nil {
		log.Fatalf("数据库连接失败: %v", err)
	}

	db.SingularTable(true) // 设置表名为单数
	if conf.Setting.RunMode != "release" {
		db.LogMode(true)
	}
	db.DB().SetMaxIdleConns(10)
	db.DB().SetMaxOpenConns(100)

	initModel() // 校验数据表
	initAdmin() // 校验admin及必填数据
}

// Instance 返回数据库连接实例
func Instance() *gorm.DB {
	once.Do(initDB)
	return db
}
